package com.sfac.javaEE.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter(filterName="authFilter", urlPatterns={"/*"})
public class AuthFilter implements Filter {
    public static List<String> ALLOW_LIST = new ArrayList<String>() {{
        add("/login");
        add("/login");
        add("/register");
        add("/static");
        add("/logout");
    }};

    // /login | /static/js/main.js
    public boolean checkUri(String uri) {
        String result = ALLOW_LIST.stream()
                .filter(item -> item.equals(uri) || uri.startsWith(item))
                .findFirst()
                .orElse(null);
        return result != null;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 获取请求 uri
        String uri = req.getRequestURI();
        // 如果 uri 满足放行列表规则 或者 登录 放行，否则 重定向到登录页面
        if (checkUri(uri) || req.getSession().getAttribute("user") != null) {
            chain.doFilter(req, resp);
        } else {
            resp.sendRedirect("/login");
        }
    }
}
